<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\weixin\request;

use extend\weixin\BaseRequest;
use extend\weixin\WxConf;
use extend\weixin\WxPay;
use yii\helpers\Json;

/**
 * 国内退款
 * ```php
 *  $request = new DomesticRefund([
 *       'out_trade_no' => 'LS23002554125464651',
 *       'out_refund_no' => 'LS23002554125464652',
 *       'reason' => '退还押金',
 *       'amount' => [
 *           'refund' => 100,
 *           'total' => 100,
 *           'currency' => 'CNY',
 *       ],
 *  ], '退还押金');
 *
 *  $wxClient = \extend\Extend::wxpay()->setRequest($request);
 *  $state = $wxClient->execute();
 *  if ($state) {
 *       var_export($wxClient->result);
 *  } else {
 *       echo $wxClient->error;
 *  }
 *  ```
 *
 * @auther clevstn
 * @since 1.0
 */
class DomesticRefund extends BaseRequest
{
    private $_requestOptions = [];
    private $_serviceName;

    /**
     * @param array $requestOptions body参数
     * @param string $serviceName 服务名称
     * @param null|string $notifyUri 回调通知URI
     * @link https://pay.weixin.qq.com/docs/merchant/apis/mini-program-payment/create.html
     */
    public function __construct(array $requestOptions, $serviceName, $notifyUri = null)
    {
        if (!empty($notifyUri)) {
            $requestOptions['notify_url'] = WxConf::MERCHANT_NOTIFY_DOMAIN . $notifyUri;
        }

        $this->_requestOptions = $requestOptions;
        $this->_serviceName = $serviceName;
    }

    public function getRequestOptions()
    {
        return [
            'json' => $this->_requestOptions,
            'verify' => false,
        ];
    }

    public function getChain()
    {
        return '/v3/refund/domestic/refunds';
    }

    public function getMethodAsync()
    {
        return 'postAsync';
    }

    public function getServiceName()
    {
        return $this->_serviceName;
    }

    public function responseCallback($response, WxPay $wxpay)
    {
        $result = Json::decode((string)$response->getBody());
        $refundStatus = $result['status'];
        $refundStateLabels = ['SUCCESS' => '微信退款成功', 'CLOSED' => '微信退款关闭', 'PROCESSING' => '微信退款处理中', 'ABNORMAL' => '微信退款异常'];
        if (!in_array($refundStatus, ['SUCCESS', 'PROCESSING'])) {
            $wxpay->error = $refundStateLabels[$refundStatus] ?? '微信退款失败';
            return false;
        }

        $wxpay->result = $result;
        return true;
    }
}